package my.leetcode.solution;

public class P2 {

    public static void main(String[] args) {
        ListNode t;
        ListNode n1 = new ListNode(9);
        t = n1.next = new ListNode(9);
        t.next = new ListNode(9);

        ListNode n2 = new ListNode(9);
        t = n2.next = new ListNode(9);
        t.next = new ListNode(9);

        ListNode r = addTwoNumbers(n1, n2);
        while(r != null) {
            System.out.print(r.val);
            r = r.next;
        }
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int next = 0, v1, v2;
        ListNode r = new ListNode(), now = r, t1 = l1, t2 = l2;

        do {
            v1 = t1 == null ? 0 : t1.val;
            v2 = t2 == null ? 0 : t2.val;
            int v = v1 + v2 + next;
            next = v / 10;
            now.val = v % 10;
            t1 = t1 == null ? null : t1.next;
            t2 = t2 == null ? null : t2.next;
            if(t1 == null && t2 == null) {
                if(next != 0) {
                    now = now.next = new ListNode();
                    now.val = next;
                }
                break;
            }
            now = now.next = new ListNode();
        } while(true);

        return r;
    }

    public static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  }
}
